import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/setting/widgets/base/index.dart";
import "package:ct_pa_majordomo/pages/device/lock/setting/widgets/bound_gateways/index.dart";
import "package:ct_pa_majordomo/pages/device/lock/setting/widgets/lock_sound/index.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:provider/provider.dart";
import "package:ttlock_flutter/ttlock.dart";
import "package:ct_pa_majordomo/pages/device/lock/lock_wifi/index.dart";

import "../api.dart";

class Setting extends StatefulWidget {
  final Map? info;
  const Setting({super.key, this.info});

  @override
  State<StatefulWidget> createState() => _SettingState();

}

class _SettingState extends State<Setting> {

  Map _lock = {};

  void _removeLock(lockId) async {
    TTLock.getBluetoothState((state) {
      if (state == TTBluetoothState.turnOn) {
        EasyLoading.show();
        TTLock.resetLock(_lock?["lockData"], () async {
          await lockApi.removeLock(lockId);
          EasyLoading.showSuccess("删除成功");
          Stacker.pushNamedAndRemoveUntil(Keys.DEVICE_LOCK, ModalRoute.withName(Keys.MAIN));
        }, (errorCode, errorMsg) {
          EasyLoading.showToast(errorMsg);
        });
      } else {
        EasyLoading.showToast("请打开蓝牙后重试");
      }
    });
  }

  void _removeBadLock(lockId) {
    String password = '';
    taiDialog(
      context: context,
      title: "移除坏锁",
      child: TextField(
        obscureText: true,
        decoration: const InputDecoration(
          hintText: "请输入登录密码",
        ),
        onChanged: (value) {
          setState(() {
            password = value;
          });
        },
      ),
      onConfirm: (BuildContext taiContext) async {
        if (password.isEmpty) {
          EasyLoading.showToast("请输入登录密码");
          return;
        }
        try {
          Map<String, dynamic> params = {
            "lockId": lockId,
            "password": password,
          };
          await lockApi.markLockBroken(int.parse(lockId), params);
          EasyLoading.showSuccess("移除坏锁");
          Stacker.pushNamedAndRemoveUntil(Keys.DEVICE_LOCK, ModalRoute.withName(Keys.DEVICE_LOCK_DETAIL));
        } catch (error) {
          print(error);
        } finally {
          EasyLoading.dismiss();
        }
      },
    );
  }

  @override
  void initState() {
    Map lock = Provider.of<CommonState>(context, listen: false).lock ?? {};
    setState(() {
      _lock = lock;
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        title: const Text("设置", style: TextStyle(color: Colors.white),),
        centerTitle: true,
        backgroundColor: ThemeVars.colorPrimaryDark,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(ThemeVars.paddingPage),
        children: [
          MenuBlock(
            items: [
              MenuBlockItem(
                text: "基本信息",
                prefix: const Icon(Icons.info_outline, color: ThemeVars.colorPrimary,),
                onTap: () {
                  Map lock = Provider.of<CommonState>(context, listen: false).lock ?? {};
                  Stacker.pushNamed(Keys.DEVICE_LOCK_SETTING_BASE, arguments: lock);
                }
              )
            ]
          ),
          const SizedBox(height: 12,),
          MenuBlock(
            items: [
              if (_lock?["type"] == 1) MenuBlockItem(
                text: "网关",
                prefix: const Icon(Icons.wifi, color: ThemeVars.colorPrimary,),
                onTap: () {
                  Stacker.pushNamed(Keys.DEVICE_LOCK_SETTING_BOUND_GATEWAY, arguments: int.parse(_lock?["lockId"]));
                }
              ),
              if (_lock?["type"] == 2) MenuBlockItem(
                text: "wifi",
                prefix: const Icon(Icons.wifi, color: ThemeVars.colorPrimary,),
                onTap: () {
                  Stacker.pushNamed(Keys.DEVICE_LOCK_WIFI, arguments: {
                    "lockData": _lock?["lockData"],
                    "lockId": int.parse(_lock?["lockId"]),
                    "type": ConfigType.sett,
                    "wifi": _lock?["wifiName"],
                  });
                }
              ),
              MenuBlockItem(
                text: "自动闭锁",
                prefix: const Icon(Icons.lock_clock_outlined, color: ThemeVars.colorPrimary,),
                onTap: () {
                  Stacker.pushNamed(Keys.DEVICE_LOCK_SETTING_AUTO_LOCK, arguments: _lock);
                },
              ),
              MenuBlockItem(
                text: "锁声音",
                prefix: const Icon(Icons.surround_sound_outlined, color: ThemeVars.colorPrimary,),
                onTap: () {
                  Stacker.pushNamed(Keys.DEVICE_LOCK_SETTING_SOUND, arguments: _lock);
                },
              )
            ]
          ),
          Padding(
            padding: const EdgeInsets.only(top: 40),
            child: Button(
              radius: 5,
              type: ButtonType.danger,
              onPressed: () {
                _removeLock(_lock?["lockId"]);
              },
              child: const Text("删除锁")
            ),
          ), 
          Padding(
            padding: const EdgeInsets.only(top: 12),
            child: GestureDetector(
              onTap: () {
                _removeBadLock(_lock?["lockId"]);
              },
              child: Text("移除坏锁", textAlign: TextAlign.right, style: TextStyle(color: ThemeVars.colorTextTer),),
            ),
          )
        ],
      ),
    );
  }

}